package com.ttdevs.testmediaplayer;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.IBinder;
import android.util.Log;

public class MediaPlayerService extends Service {

	private static final String TAG = MediaPlayerService.class.getName();

	private ServerSocket server;
	private Socket socket;
	private MediaPlayer mediaPlayer;

	@Override
	public void onCreate() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				Log.d(TAG, "start service...");
				try {
					server = new ServerSocket(9559);
					Log.d(TAG, "start socket...");
					socket = server.accept();

					int clientPort = socket.getPort();
					String IP = socket.getInetAddress().getHostAddress();
					String url = "http://" + IP + ":" + clientPort;

					Log.d(TAG, "url:" + url);

					mediaPlayer = new MediaPlayer();
					mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
					mediaPlayer.setDataSource(url);
					mediaPlayer.setOnErrorListener(new OnErrorListener() {
						
						@Override
						public boolean onError(MediaPlayer mp, int what, int extra) {
							// TODO Auto-generated method stub
							return false;
						}
					});
					mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
						@Override
						public void onPrepared(MediaPlayer mp) {
							Log.d(TAG, "prepared and start");
							mp.start();
						}
					});
					mediaPlayer.prepareAsync();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}